

"""
drf 框架 能够帮助我们实现  序列化和反序列化的功能  (对象和字典的相互转换)


BookInfo(对象)        ---序列化器类--->             字典

豆子                  ---豆浆机--->              豆浆


序列化器类
    ① 将对象转换为字典
    ② 将字典转换为对象  -- 反序列化


序列化器类的定义
    ① 参考模型来定义就可以了


class 序列化器名字(serializers.Serializer):
    字段名=serializer.类型(选项)


    字段名和模型字段名一致
    字段的类型和模型的类型一致

"""
############################################################外键操作
from rest_framework import serializers

from rest_framework import serializers
from book.models import BookInfo

class Peopl2eRelatedSerializer(serializers.Serializer):

    id=serializers.IntegerField()
    name=serializers.CharField()
    password=serializers.CharField()

class BookInfoSerializer(serializers.Serializer):
    id = serializers.IntegerField(read_only=True)
    name = serializers.CharField(write_only=True, max_length=10, min_length=5)
    pub_date = serializers.DateField(required=True)
    readcount = serializers.IntegerField(max_value=100000, min_value=1)

    #
    people=PeopleInfoSerializer(many=True)

    # 单个字段验证
    def validate_readcount(self, value):

        # 写 额外的检测代码
        if value < 0:
            # raise Exception('阅读量不能为负数')

            # rest_framework.exceptions.ValidationError:
            raise serializers.ValidationError('阅读量不能为负数')

        return value

    # 多个字段验证
    # attrs = data
    # def validate(self, attrs):
    def validate(self, data):

        readcount = data.get('readcount')
        commentcount = data.get('commentcount')

        # if readcount<0:
        #     raise serializers.ValidationError('')

        if commentcount > readcount:
            raise serializers.ValidationError('评论量不能大于阅读量')

        return data



    ###########如果我们的序列化器是继承自Serialzier 当调用序列化器的save方法的时候,
    # ############会触发调用 序列化器的create方法
    def create(self, validated_data):

        return BookInfo.objects.create(**validated_data)


    def update(self, instance, validated_data):

        instance.name=validated_data.get('name',instance.name)
        instance.pub_date=validated_data.get('pub_date',instance.pub_date)
        instance.readcount=validated_data.get('readcount',instance.readcount)
        instance.commentcount=validated_data.get('commentcount',instance.commentcount)
        instance.save()
        return instance









################定义人物模型对应的序列化器#########

class PeopleInfoSerializer(serializers.Serializer):

    id=serializers.IntegerField()
    name=serializers.CharField()
    password=serializers.CharField()
    description=serializers.CharField()
    is_delete=serializers.BooleanField()



####################################


class BookInfoModelSerializer(serializers.ModelSerializer):
    # name=serializers.CharField(max_length=10,min_length=5,required=True)
    class Meta:
        model=BookInfo
        fields='__all__'       ####使用fields来明确字段，__all__表名包含所有字段
        # fields=['id','name']
        # exclude=['id','name']               #使用exclude可以明确排除掉哪些字段


        # 只读字段列表   仅用于序列化输出的字段
        read_only_fields=['id','name','pub_date']


        # 选项设置  使用extra_kwargs参数为ModelSerializer添加或修改原有的选项参数
        extra_kwargs = {
            # '字段名': { '选项名':value, },
            'name': {
                'max_length':40,
                'min_length':10
            }
        }













